package com.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;
import java.lang.reflect.Method;


/**
 * @author xiangjun.deng
 * email 17670934918dxj@sina.com
 * @date 2021/8/11 14:51
 * @desc
 */

//@Aspect
@Component
public class TxAdvice {
    @Autowired
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Pointcut(value = "@annotation(com.CustomTransaction)")
    public void pt(){}
    @Around("pt()")
    public Object transactionManager(ProceedingJoinPoint pjp) throws Throwable {

            DataSourceTransactionManager ptm = new DataSourceTransactionManager(dataSource);
            TransactionDefinition definition = new DefaultTransactionDefinition();

            TransactionStatus transactionStatus = ptm.getTransaction(definition);
            Object res = null;
            try {
                res = pjp.proceed();
            } catch (Throwable throwable) {
                ptm.rollback(transactionStatus);
                return res;
            }

            ptm.commit(transactionStatus);

            return res;
        }




}
